package com.fixme4trade.persistence;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.slf4j.Logger;

import com.fixme4trade.domain.Customer;
import com.fixme4trade.domain.Seller;
import com.fixme4trade.domain.User;

import br.gov.frameworkdemoiselle.message.MessageContext;
import br.gov.frameworkdemoiselle.stereotype.PersistenceController;
import br.gov.frameworkdemoiselle.template.JPACrud;

@PersistenceController
public class UserDAO extends JPACrud<User, Long> {
	
	private static final long serialVersionUID = 1L;

	@Inject
	@SuppressWarnings("unused")
	private Logger logger;
	
	@Inject
	private EntityManager em;
	
	public boolean checkUsernamePassword(String username, String password) {		
		
		//TypedQuery<Long> queryUsernamePassword = em.createQuery(
		//	      "SELECT COUNT(*) FROM User u WHERE u.username='"+username+"' AND u.password='"+password+"' ", Long.class);
		Query queryUsernamePassword = em.createNativeQuery(
				"SELECT * FROM User u WHERE u.username='"+username+"' AND u.password='"+password+"' ", User.class);
				
		//boolean logonFail = queryUsernamePassword.getSingleResult() == 1;
		boolean logonSuccess = !queryUsernamePassword.getResultList().isEmpty();
		
		if (!logonSuccess) {
			//TypedQuery<Long> queryUsername = em.createQuery(
			//	      "SELECT COUNT(*) FROM User u WHERE u.username='"+username+"'", Long.class);
			Query queryUsername = em.createNativeQuery(
					"SELECT * FROM User u WHERE u.username='"+username+"'", User.class);
			if (!queryUsername.getResultList().isEmpty()) {
				//Mensagem usuario incorreto
			} else {
				//Mensagem senha incorreta
			}			
		}
		
		return logonSuccess;
	}
	
	public Seller getSellerByUser (User user) {	
		return em.find(Seller.class, user.getId());
	}
	
	public Customer getCustomerByUser (User user) {
		return em.find(Customer.class, user.getId());
	}

	public Object getUserByUsername(String username) {
		TypedQuery<User> query = em.createQuery(
			      "SELECT u FROM User u WHERE u.username='"+username+"'", User.class);
		
		return query.getSingleResult();
	}
}
